package com.briup.pts.service.impl;

import com.briup.pts.service.UploadService;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.util.UUID;

@Setter
@ConfigurationProperties(prefix = "upload.oss")
@Service
public class UploadServiceImpl implements UploadService {

    private String accessKey;
    private String secretKey;
    private String bucketName;
    private String baseUrl;

    @Override
    public String uploadToOss(MultipartFile file) {
        //构造一个 自动选择区域的 配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        // 创建文件上传 管理器
        UploadManager uploadManager = new UploadManager(cfg);

        // 根据ak和sk 以及 bucketName获取上传凭证
        Auth auth = Auth.create(accessKey,
                secretKey);
        String uploadToken = auth.uploadToken(
                bucketName);

        String fileName = generatorFileName(file);

        // 上传数据，指定文件在OSS服务中的名称
        try {
            uploadManager.put(file.getInputStream(), fileName,
                    uploadToken, null, null);
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败，请重新上传");
        }
        // 返回URL路径
        return String.format(baseUrl, fileName);
    }

    private String generatorFileName(MultipartFile file) {
        // a.txt.jpg.txt
        String[] infos = file.getOriginalFilename().split("[.]");
        // 获取文件的后缀
        String suffix = infos[infos.length - 1];
        String date = LocalDate.now().toString();
        String name = UUID.randomUUID()
                .toString().replace("-", "");

        return String.format("%s/%s.%s", date, name, suffix);
    }
}
